//
//  HomeViewController.m
//  easystudy
//
//  Created by kane on 15/6/1.
//  Copyright (c) 2015年 kane. All rights reserved.
//

#import "HomeViewController.h"
#import "CityViewController.h"
#import "SearchViewController.h"
#import "MessageViewController.h"
#import "MJRefresh.h"
#import "NewsListCell.h"
#import "ChannelManageViewController.h"
#import "SearchSubjectViewController.h"
#import "ContentViewController.h"
#import "FilterContentView.h"

@interface HomeViewController ()<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate,MJRefreshBaseViewDelegate,ChannelDelagate,NewsListCellDelegate,ContentViewDelegate>
{
    __weak IBOutlet UISearchBar *_searchBar;
    __weak IBOutlet UIButton *_cityButton;
    __weak IBOutlet UITableView *dataTable;
    __weak IBOutlet UIScrollView *subjectScroll;
    __weak IBOutlet UIView *searchBgView;
    __weak IBOutlet UIButton *addBtn;
    
    NSMutableArray *dataList;
    
    MJRefreshHeaderView *header;
    EmptyView *emptyView;
    
    NSMutableArray *subjectList;
    NSInteger currentIndex;

    FilterContentView *_filterView;
    
    
}
@property (nonatomic,strong) NSArray *classArray;

@end

@implementation HomeViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    dataList = [NSMutableArray array];
    subjectList = [NSMutableArray array];
    currentIndex = 0;
    self.edgesForExtendedLayout = UIRectEdgeNone;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeNightMode) name:kChangeNightMode object:nil];
    [self initUI];
    [self initRefreshUI];
    [self changeNightMode];
    [self reloadSubjectList];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addUserchannel:) name:@"addUserchannel" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deleteUserchannel:) name:@"deleteUserchannel" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeAry:) name:@"arrayChange" object:nil];
}

- (void)initUI
{
    searchBgView.layer.cornerRadius = 15;
    _searchBar.layer.cornerRadius = 15;
    _searchBar.layer.masksToBounds = YES;
    subjectScroll.showsHorizontalScrollIndicator = NO;
    
//    emptyView = [[EmptyView alloc] init];
//    [self.view insertSubview:emptyView belowSubview:dataTable];

    
    for (UIView *subView in _searchBar.subviews) {
        for (UIView *sub in subView.subviews) {
            if (![sub isKindOfClass:NSClassFromString(@"UISearchBarTextField")]) {
                [sub removeFromSuperview];
            }
        }
    }
    [self reloadSubjectScrollUI];
}

- (void)changeNightMode
{
    self.view.backgroundColor = KKColor_Black_White;
    for (int i = 0; i < subjectList.count; i++) {
        UIButton *btn = (UIButton *)[subjectScroll viewWithTag:CellOffset+i];
        [btn setTitleColor:KKColor_White_Black forState:UIControlStateNormal];
    }
}

- (void)reloadSubjectList
{
    NSDictionary *params = @{@"cs_cid":[[UserEntity sharedUser] getUserID]};
    [WebService findUserMarkChannelList:params WithBlock:^(id result, NSError *error) {
        if (!error) {
            if ([result[@"errcode"] integerValue] == 0) {
                NSArray *channelAry = result[@"result"][@"subchannel"][@"value"];
                [subjectList removeAllObjects];
                [subjectList addObject:@{@"channel_name":@"推荐",@"cs_channelid":@"-1"}];
                [subjectList addObjectsFromArray:channelAry];
                [self reloadSubjectScrollUI];
            }
        }
    }];
}

-(void)reloadSubjectScrollUI
{
    [subjectScroll.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    NSInteger totalLegth = 0;
    for (NSInteger i= 0; i<subjectList.count; i++) {
        NSDictionary *item = subjectList[i];
        NSString *title = item[@"channel_name"];
        UIButton *subjectBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [subjectBtn setTitleColor:KKColor_White_Black forState:UIControlStateNormal];
        [subjectBtn setTitleColor:AppColor forState:UIControlStateSelected];
        [subjectBtn.titleLabel setFont:[UIFont systemFontOfSize:15]];
        subjectBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
        [subjectBtn addTarget:self action:@selector(subjectBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        NSInteger wordNum = title.length;
        subjectBtn.frame = CGRectMake(10+totalLegth,0,wordNum*15, 37);
        totalLegth = totalLegth+wordNum*15+10;
        subjectBtn.tag = CellOffset + i;
        [subjectBtn setTitle:title forState:UIControlStateNormal];
        [subjectScroll addSubview:subjectBtn];
        UIView *redPoint = [[UIView alloc] initWithFrame:CGRectMake(-2, 4, 8, 8)];
        redPoint.tag = CellOffset*5+i;
        NSDictionary *dict = subjectList[i];
        if ([[dict[@"is_new"] convertToString] isEqualToString:@"y"]) {
            redPoint.hidden = NO;
        }else {
            redPoint.hidden = YES;
        }
        redPoint.layer.cornerRadius = 4;
        redPoint.backgroundColor = [UIColor redColor];
        [subjectBtn addSubview:redPoint];
        if (i == currentIndex) {
            subjectBtn.selected = YES;
        }
    }
    subjectScroll.contentSize = CGSizeMake(totalLegth+10, 32);
}

- (void)initRefreshUI
{
    header = [MJRefreshHeaderView header];
    header.scrollView = dataTable;
    header.delegate = self;
    [header beginRefreshing];
}

- (void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView
{
    if (currentIndex == 0) {
        NSDictionary *params = @{@"cs_cid":[[UserEntity sharedUser] getUserID],@"a_channelid":@"",@"a_status":@"2"};
        [WebService findArticleList:params WithBlock:^(id result, NSError *error) {
            if (!error) {
                if ([result[@"errcode"] integerValue] == 0) {
                    NSArray *dataAry = result[@"result"][@"article"][@"value"];
                    [dataList removeAllObjects];
                    [dataList addObjectsFromArray:dataAry];
                    [dataTable reloadData];
                }
            }
            [refreshView endRefreshing];
        }];
    }else{
        NSDictionary *item = [subjectList objectAtIndex:currentIndex];
        NSDictionary *params = @{@"cs_cid":[[UserEntity sharedUser] getUserID],@"a_channelid":[item[@"cs_channelid"] convertToString],@"a_status":@""};
        [WebService findArticleList:params WithBlock:^(id result, NSError *error) {
            if (!error) {
                if ([result[@"errcode"] integerValue] == 0) {
                    [dataList removeAllObjects];
                    NSArray *dataAry = result[@"result"][@"article"][@"value"];
                    [dataList addObjectsFromArray:dataAry];
                    [dataTable reloadData];
                }
            }
            [refreshView endRefreshing];
        }];
    }
}


#pragma ChannelManageViewController delegate

- (void)selectedChannelChanged:(NSInteger)newIndex;
{
    if (newIndex == currentIndex) {
        return;
    }
    UIButton *prevBtn = [subjectScroll viewWithTag:currentIndex + CellOffset];
    prevBtn.selected = NO;
    UIButton *newBtn = [subjectScroll viewWithTag:newIndex + CellOffset];
    newBtn.selected = YES;
    currentIndex = newBtn.tag - CellOffset;
    [header beginRefreshing];
}

-(void)sendSubjectAryValue:(NSArray *)array
{
    [subjectList removeAllObjects];
    [subjectList addObjectsFromArray:array];
    
    [self reloadSubjectScrollUI];
}




#pragma mark -userAction
-(void)subjectBtnClick:(UIButton *)sender
{
    NSDictionary *dict = subjectList[currentIndex];
    NSMutableDictionary *newDict = [NSMutableDictionary dictionaryWithDictionary:dict];
    [newDict removeObjectForKey:@"is_new"];
    [subjectList replaceObjectAtIndex:currentIndex withObject:newDict];
    if (sender.tag == currentIndex + CellOffset) {
        return;
    }
    UIButton *prevBtn = [subjectScroll viewWithTag:currentIndex + CellOffset];
    prevBtn.selected = NO;
    
    sender.selected = YES;
    currentIndex = sender.tag - CellOffset;
    [header beginRefreshing];
}

- (IBAction)leftSwipe:(id)sender{
    if (currentIndex == subjectList.count-1) {
        return;
    }
//    [header beginRefreshing];
    if (currentIndex < subjectList.count) {
        UIButton *prevBtn = [subjectScroll viewWithTag:currentIndex + CellOffset];
        prevBtn.selected = NO;
        UIButton *newBtn = [subjectScroll viewWithTag:currentIndex + CellOffset+1];
        newBtn.selected = YES;
        currentIndex ++;
        [header beginRefreshing];
        if (newBtn.minX > self.view.width/2 -40 && currentIndex < subjectList.count-1) {
            [subjectScroll setContentOffset:CGPointMake(newBtn.frame.origin.x - self.view.width/2, 0) animated:YES];
        }
//        NSLog(@"%@")
//        if (subjectScroll.contentSize.width > ((self.view.width + newBtn.width)/2 + newBtn.minX)) {
//            [subjectScroll setContentOffset:CGPointMake(subjectScroll.contentSize.width - self.view.width, 0) animated:YES];
//        }else{
//            [subjectScroll setContentOffset:CGPointMake((newBtn.minX + newBtn.width / 2) - (self.view.width / 2), 0) animated:YES];
//        }
        CATransition *animation = [CATransition animation];
        animation.duration = 0.35f;
        animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
        animation.fillMode = kCAFillModeForwards;
        animation.type = kCATransitionPush;
        animation.subtype = kCATransitionFromRight;
        [dataTable.layer addAnimation:animation forKey:@"animation"];
    }
}

- (IBAction)rightSwipe:(id)sender{
    if (currentIndex > 0) {
        UIButton *prevBtn = [subjectScroll viewWithTag:currentIndex + CellOffset];
        prevBtn.selected = NO;
        UIButton *newBtn = [subjectScroll viewWithTag:currentIndex + CellOffset-1];
        newBtn.selected = YES;
        currentIndex --;
        [header beginRefreshing];
        if (newBtn.minX+newBtn.width/2 <=self.view.width) {
            [subjectScroll setContentOffset:CGPointMake(0, 0) animated:YES];
        }else{
            [subjectScroll setContentOffset:CGPointMake(newBtn.frame.size.width, 0) animated:YES];
        }
        CATransition *animation = [CATransition animation];
        animation.duration = 0.35f;
        animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
        animation.fillMode = kCAFillModeForwards;
        animation.type = kCATransitionPush;
        animation.subtype = kCATransitionFromLeft;
        [dataTable.layer addAnimation:animation forKey:@"animation"];
    }
}

- (IBAction)addBtnClick:(UIButton *)sender {
    ChannelManageViewController *channelVc = [[ChannelManageViewController alloc] init];
    channelVc.channelAry = subjectList;
    channelVc.selectedIndex = currentIndex;
    channelVc.delegate = self;
    channelVc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:channelVc animated:YES];
}

- (IBAction)shareBtnPress:(id)sender {
    NSMutableArray *items = [NSMutableArray arrayWithObject:@"http://www.baidu.com"];
    UIActivityViewController *activity = [[UIActivityViewController alloc] initWithActivityItems:items applicationActivities:nil];
    [self presentViewController:activity animated:YES completion:nil];
    
}

-(void)addUserchannel:(NSNotification *)notify
{
    NSDictionary *dict = notify.object;
    if (subjectList.count > 2) {
        [subjectList insertObject:dict atIndex:2];
    }else{
        [subjectList addObject:dict];
    }
    [self reloadSubjectScrollUI];
}


-(void)changeAry:(NSNotification *)notify
{
    NSArray *ary = notify.object;
    [subjectList removeAllObjects];
    [subjectList addObjectsFromArray:ary];
}

-(void)deleteUserchannel:(NSNotification *)notify
{
    NSDictionary *dict = notify.object;
    [subjectList enumerateObjectsUsingBlock:^(NSDictionary *item, NSUInteger idx, BOOL *stop) {
        if ([[dict[@"cs_channelid"] convertToString] isEqualToString:[item[@"cs_channelid"] convertToString]]) {
            [subjectList removeObject:item];
            *stop = YES;
        }
    }];
    [self reloadSubjectScrollUI];
    [self subjectBtnClick:[subjectScroll viewWithTag:CellOffset]];
}


#pragma mark - UITableView DataSource && Delegate

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *item = dataList[indexPath.row];
    NSString *imgString = [item[@"a_picture"] convertToString];
    NSArray *photoAry = [imgString componentsSeparatedByString:@","];
    NSInteger type = 0;
    if (photoAry.count >= 3) {
        type = 3;
    }else if (photoAry.count >= 1){
        type = 1;
    }
    switch (type) {
        case 0:
            return 85;
            break;
        case 1:
            return 90;
            break;
        case 3:
            return 170;
            break;
        default:
            break;
    }
    return 0;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return dataList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"HomeClassCell";
    NewsListCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[NewsListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    cell.dataIndex = indexPath.row;
    cell.delegate = self;
    NSDictionary *dict = dataList[indexPath.row];
    [cell setupNewsData:dict];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSDictionary *item = dataList[indexPath.row];
    ContentViewController *contentVC = [[ContentViewController alloc] init];
    contentVC.dataInfo = item;
    contentVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:contentVC animated:YES];
}

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    SearchSubjectViewController *subVC = [[SearchSubjectViewController alloc] init];
    subVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:subVC animated:NO];
    return NO;
}
#pragma mark - NewListCellDelegate
- (void)clickFilterButton:(NSInteger)index withCGRect:(CGRect)rect
{
    _filterView.typeBtn1.hidden = YES;
    _filterView.typeBtn2.hidden = YES;
    NSDictionary *item = dataList[index];
    NSArray *nameAry = item[@"channel"];
    NSMutableArray *nameList = [NSMutableArray array];
    for (NSDictionary *dict in nameAry) {
        [nameList addObject:dict[@"channel_name"]];
    }
    NSString *source = item[@"source"];
    [_filterView.titleBtn setTitle:@"标题党" forState:UIControlStateNormal];
    [_filterView.contentBtn setTitle:@"内容质量差" forState:UIControlStateNormal];
    [_filterView.sourceBtn setTitle:[NSString stringWithFormat:@"来源:%@",source] forState:UIControlStateNormal];
    if (nameList.count >= 1) {
        //
        [_filterView.channelBtn setTitle:nameList[0] forState:UIControlStateNormal];
    }
    if (nameList.count >=2) {
        [_filterView.typeBtn1 setTitle:nameList[1] forState:UIControlStateNormal];
        _filterView.typeBtn1.hidden = NO;
    }
    if (nameAry.count >= 3) {
        [_filterView.typeBtn2 setTitle:nameList[2] forState:UIControlStateNormal];
        _filterView.typeBtn2.hidden = NO;
    }
    if(!_filterView){
        _filterView = [[[UINib nibWithNibName:@"FilterContentView" bundle:nil] instantiateWithOwner:self options:nil] objectAtIndex:0];
        _filterView.frame = CGRectMake(0, 0, fWidth_Current, fHeight_Current);
        [_filterView.contentView drawCornerRadius:5];
        _filterView.dataIndex = index;
        _filterView.delegate = self;
        [self drawButtonWithBtn:_filterView.titleBtn];
        [self drawButtonWithBtn:_filterView.contentBtn];
        [self drawButtonWithBtn:_filterView.sourceBtn];
        [self drawButtonWithBtn:_filterView.channelBtn];
        [self drawButtonWithBtn:_filterView.typeBtn1];
        [self drawButtonWithBtn:_filterView.typeBtn2];
    }
    if (rect.origin.y < fHeight_Current/2) {
        _filterView.contentView.frame = (CGRect){10,rect.origin.y+30,_filterView.contentView.size};
        _filterView.arrowImage.image = [UIImage imageNamed:@"image_up"];
        _filterView.arrowImage.frame = (CGRect){rect.origin.x-25,rect.origin.y+15,80,60};

    }else {
        _filterView.contentView.frame = (CGRect){10,rect.origin.y - _filterView.contentView.size.height ,_filterView.contentView.size};
        _filterView.arrowImage.image = [UIImage imageNamed:@"image_down"];
        _filterView.arrowImage.frame = (CGRect){rect.origin.x-25,rect.origin.y-45,80,60};
    }
    [self.view addSubview:_filterView];
}
- (void)drawButtonWithBtn:(UIButton *)button
{
    [button drawCornerRadius:15];
    [button drawBorderColor:[UIColor lightGrayColor] Width:0.5];
}

#pragma mark - ContentViewDelegate
- (void)clickShieldButton:(NSInteger)index
{
    [dataList removeObjectAtIndex:index];
    [dataTable reloadData];
    [_filterView removeFromSuperview];
    _filterView = nil;
    [self.view makeToast:@"将为你减少类似内容" position:@"center"];
}


@end
